<template>
    <div class="my-ali-upload flex flex-direction-v">
        <!-- <div :id="ossContainer"> -->
            <!--<a :id="selectFiles" href="javascript:void(0);" class='oss-btns'>选择</a>
			<a :id="postFiles" href="javascript:void(0);" class='oss-btns'>上传</a>-->
        <!-- </div> -->
        <div :id="ossFile">你的浏览器不支持flash,Silverlight或者HTML5！</div>
    </div>
</template>

<script>
import _date from "@/util/Date";

export default {
    name: "AliOssUpload",
    mounted() {
        let vm = this;
        vm.initData();
        vm.uploaderInit();
    },
    data() {
        let vm = this;
        return {
            accessid: "LTAIej2cp7PLNQma",
            accesskey: "J2MhrXC4QX2CtQPRxLTGF2BfLKGocd",
            host: "https://stdag-image.oss-cn-beijing.aliyuncs.com",
            // 上传目录名
            g_dirname: vm.dirName,
            // 先上传目录名，再上传文件名
            g_object_name: "",
            // 文件命名方式，有本地名，随机名
            g_object_name_type: "random_name", // local_name
            policyBase64: "",
            signature: "",
            uploader: {}
        };
    },
    props: {
        ossFile: {
            type: String,
            default: ""
        },
        ossContainer: {
            type: String,
            default: ""
        },
        selectFiles: {
            type: String,
            default: ""
        },
        postFiles: {
            type: String,
            default: ""
        },
        dirName: {
            type: String,
            default: ""
        },
        maxFileSize: {
            type: Number,
            default: 2097152 // 默认2m
        }
    },
    computed: {},
    methods: {
        initData() {
            let vm = this;
            let policyText = {
                expiration: "2030-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
                conditions: [
                    ["content-length-range", 0, vm.maxFileSize] // 设置上传文件的大小限制,字节单位为b
                ]
            };
            vm.policyBase64 = Base64.encode(JSON.stringify(policyText));
            let message = vm.policyBase64;
            let bytes = Crypto.HMAC(Crypto.SHA1, message, vm.accesskey, {
                asBytes: true
            });
            vm.signature = Crypto.util.bytesToBase64(bytes);
        },
        random_string(len) {
            len = len || 32;
            let chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
            let maxPos = chars.length;
            let pwd = "";
            for (let i = 0; i < len; i++) {
                pwd += chars.charAt(Math.floor(Math.random() * maxPos));
            }
            return pwd;
        },
        get_suffix(filename) {
            let pos = filename.lastIndexOf(".");
            let suffix = "";
            if (pos != -1) {
                suffix = filename.substring(pos);
            }
            return suffix;
        },
        calculate_object_name(filename) {
            let vm = this;
            if (vm.g_object_name_type == "local_name") {
                vm.g_object_name += "${filename}";
            } else if (vm.g_object_name_type == "random_name") {
                let suffix = vm.get_suffix(filename);
                //					vm.g_object_name = vm.g_dirname + vm.random_string(10) + suffix
                // 文件真实命名
                vm.g_object_name =
                    vm.g_dirname +
                    _date.dateFmt("yyyyMMddhhmmss", new Date()) +
                    "_" +
                    vm.random_string(10) +
                    suffix;
            }
            return "";
        },
        get_uploaded_object_name(filename) {
            let vm = this;
            if (vm.g_object_name_type == "local_name") {
                let tmp_name = vm.g_object_name;
                tmp_name = tmp_name.replace("${filename}", filename);
                return tmp_name;
            } else if (vm.g_object_name_type == "random_name") {
                return vm.g_object_name;
            }
        },
        set_upload_param(up, filename, ret) {
            let vm = this;
            vm.g_object_name = vm.g_dirname;
            if (filename != "") {
                let suffix = vm.get_suffix(filename);
                vm.calculate_object_name(filename);
            }
            let new_multipart_params = {
                key: vm.g_object_name,
                policy: vm.policyBase64,
                OSSAccessKeyId: vm.accessid,
                success_action_status: "200", //让服务端返回200,不然，默认会返回204
                signature: vm.signature
            };

            up.setOption({
                url: vm.host,
                multipart_params: new_multipart_params
            });

            up.start();
        },
        uploaderInit() {
            let vm = this;

            vm.uploader = new plupload.Uploader({
                runtimes: "html5,flash,silverlight,html4",
                browse_button: vm.selectFiles,
                // multi_selection: true, // 单选
                container: document.getElementById(vm.ossContainer),
                flash_swf_url: "lib/plupload-2.1.2/js/Moxie.swf",
                silverlight_xap_url: "lib/plupload-2.1.2/js/Moxie.xap",
                url: "http://oss.aliyuncs.com",
                resize: {
                    width: 800,
                    crop: true,
                    quality: 80,
                    preserve_headers: false
                },
                vm: vm,
                init: {
                    PostInit: function() {
                        let vm = this.getOption().vm;
                        document.getElementById(vm.ossFile).innerHTML = "";
                        document.getElementById(vm.ossFile).style.display =
                            "none";
                        document.getElementById(
                            vm.postFiles
                        ).onclick = function() {
                            //								vm.set_upload_param(vm.uploader, '', false);
                            return false;
                        };
                    },

                    FilesAdded: function(up, files) {
                        let vm = this.getOption().vm;
                        plupload.each(files, function(file) {
                            //								document.getElementById(vm.ossFile).innerHTML = '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ')<br/><b></b>' +
                            //									'<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>' +
                            //									'</div>';
                            document.getElementById(vm.ossFile).innerHTML =
                                '<div id="' +
                                file.id +
                                '">' +
                                "<b></b>" +
                                '<div class="progress"><div class="progress-bar" style="width: 0%"></div></div>' +
                                "</div>";
                        });
                        vm.set_upload_param(vm.uploader, "", false);
                    },

                    BeforeUpload: function(up, file) {
                        let vm = this.getOption().vm;
                        if (file.origSize > vm.maxFileSize) {
                            vm.$message.error(
                                "上传失败，可能原因是文件大小超出" +
                                    parseInt(vm.maxFileSize / 1048576) +
                                    "M"
                            );
                        } else {
                            vm.set_upload_param(up, file.name, true);
                        }
                    },

                    UploadProgress: function(up, file) {
                        let vm = this.getOption().vm;
                        if (file.origSize <= vm.maxFileSize) {
                            vm.$emit("uploadProgress", file.percent);
                            return;
                            let d = document.getElementById(file.id);
                            d.getElementsByTagName("b")[0].innerHTML =
                                "<span>" + file.percent + "%</span>";
                            let prog = d.getElementsByTagName("div")[0];
                            let progBar = prog.getElementsByTagName("div")[0];
                            progBar.style.width = 2 * file.percent + "px";
                            progBar.setAttribute("aria-valuenow", file.percent);
                        }
                    },

                    FileUploaded: function(up, file, info) {
                        let vm = this.getOption().vm;
                        if (info.status == 200) {
                            vm.$emit(
                                "fileUploaded",
                                vm.host,
                                vm.get_uploaded_object_name(file.name)
                            );
                            return;
                            document
                                .getElementById(file.id)
                                .getElementsByTagName("b")[0].innerHTML =
                                "上传成功!";
                            setTimeout(function() {
                                document.getElementById(file.id).style.display =
                                    "none";
                            }, 1000);
                            console.log(
                                "上传成功，文件名:" +
                                    vm.get_uploaded_object_name(file.name)
                            );
                        } else {
                            document
                                .getElementById(file.id)
                                .getElementsByTagName("b")[0].innerHTML =
                                info.response;
                        }
                    },

                    Error: function(up, err) {
                        let vm = this.getOption().vm;
                        console.log(err);
                    }
                }
            });

            vm.uploader.init();
        }
    }
};
</script>

<style lang="scss" scoped>
.my-ali-upload {
}
</style>

<style lang="scss">
.my-ali-upload {
    .oss-btns {
        color: #fff;
        background-color: #337ab7;
        border-color: #2e6da4;
        display: inline-block;
        padding: 6px 12px;
        margin-bottom: 0;
        font-size: 14px;
        font-weight: 400;
        line-height: 1.42857143;
        text-align: center;
        white-space: nowrap;
        text-decoration: none;
        vertical-align: middle;
        -ms-touch-action: manipulation;
        touch-action: manipulation;
        cursor: pointer;
        -webkit-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        user-select: none;
        background-image: none;
        border: 1px solid transparent;
        border-radius: 4px;
    }
    a.oss-btns:hover {
        background-color: #3366b7;
    }
    .progress {
        margin-top: 2px;
        width: 200px;
        height: 14px;
        margin-bottom: 10px;
        overflow: hidden;
        background-color: #f5f5f5;
        border-radius: 4px;
        -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
        box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
    }
    .progress-bar {
        background-color: rgb(92, 184, 92);
        background-image: linear-gradient(
            45deg,
            rgba(255, 255, 255, 0.14902) 25%,
            transparent 25%,
            transparent 50%,
            rgba(255, 255, 255, 0.14902) 50%,
            rgba(255, 255, 255, 0.14902) 75%,
            transparent 75%,
            transparent
        );
        background-size: 40px 40px;
        box-shadow: rgba(0, 0, 0, 0.14902) 0px -1px 0px 0px inset;
        box-sizing: border-box;
        color: rgb(255, 255, 255);
        display: block;
        float: left;
        font-size: 12px;
        height: 20px;
        line-height: 20px;
        text-align: center;
        transition-delay: 0s;
        transition-duration: 0.6s;
        transition-property: width;
        transition-timing-function: ease;
        width: 266.188px;
    }
}
</style>